﻿// -----------------------------------------------------------------------
// <copyright file="ProgramHelpers.cs" company="None">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ODataTestLauncherConsole
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography.X509Certificates;
    using System.Net;
    using System.Diagnostics;
   
    using System.Diagnostics.Contracts;
    using System.IO;
    
    using System.Text.RegularExpressions;
    using System.Configuration;
    using System.Xml;
    using ODataTestFrameworkCore.shared;
    using System.Threading;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public partial class ProgramHelper
    {

        public static void RaiseEmailAlert(string ResultFileName,string EmailList)
        {
            string resultXML = ResultFileName.Replace(".xlsx",string.Empty);
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(resultXML);
            XmlNodeList resultNodes = xDoc.DocumentElement.SelectNodes("//Results/Result");
            XmlNode summary = xDoc.DocumentElement.SelectSingleNode("//ExecutionSummary");

            int TotalTestCount = Convert.ToInt32(summary.Attributes["TotalTestCount"].Value);
            int Passed = Convert.ToInt32(summary.Attributes["Passed"].Value);
            int Error = Convert.ToInt32(summary.Attributes["Error"].Value);
            int Failed = TotalTestCount - Passed;

            double PassPercentage = 100 * ((double)Passed / (double)TotalTestCount);
            FileInfo fn = new FileInfo(ResultFileName);

            string messageSubject = string.Format("Execution '{0}' Status Passed{1:0.00}%", fn.Name.Replace(".xslx",string.Empty), PassPercentage);

            string messageBody = string.Format("Execution Summary Total={0}, Passed={1}, Failed={2}",
                TotalTestCount, Passed, Failed);
                       
            messageBody = messageBody + Environment.NewLine + "LogFiles" + Environment.NewLine ;
            messageBody = messageBody +resultXML + Environment.NewLine;
            messageBody = messageBody + ResultFileName + Environment.NewLine;

            messageBody = messageBody + string.Format("This is an auto generated email by 'MDM Service Monitoring Tool'on the behalf of '{0}'{1}", Environment.UserName, Environment.NewLine);
            EmailHelper.SendEmail(EmailList, messageSubject, messageBody);

        }
        public static bool CreateExcelReport(string InputXMLFile, string outputExcelFileName)
        {


            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(InputXMLFile);
            XmlNodeList resultNodes = xDoc.DocumentElement.SelectNodes("//Results/Result");
            XmlNode summary = xDoc.DocumentElement.SelectSingleNode("//ExecutionSummary");

            Microsoft.Office.Interop.Excel.Range thisCell = null; ;
            
            try
            {
                using (ExcelHelper excelHelper = new ExcelHelper(outputExcelFileName))
                {
                    
                    int curLeft=Console.CursorLeft;
                        int curTop= Console.CursorTop;
                    for (int k = 0; k < summary.Attributes.Count; k++)
                    {
                        thisCell = excelHelper.SetCell(summary.Attributes[k].Name + "=" + summary.Attributes[k].Value, 1, k + 1, 1);
                        thisCell.Interior.ColorIndex = 18;
                    }


                    for (int i = 0; i < resultNodes.Count; i++)
                    {

                        for (int j = 0; j < resultNodes[i].Attributes.Count; j++)
                        {
                            if (i == 0)
                            {
                                thisCell = excelHelper.SetCell(resultNodes[i].Attributes[j].Name, i + 1, j + 1, 2);
                                thisCell.Interior.ColorIndex = 16;

                            }
                            thisCell = excelHelper.SetCell(resultNodes[i].Attributes[j].Value, i + 2, j + 1, 2);
                            if (resultNodes[i].Attributes[j].Name == "QueryURL")
                            {
                                /// If hyper links are too long Excel autiomation with throw exception 
                                /// Just igmoring the exception 
                                try
                                {

                                    thisCell.Hyperlinks.Add(thisCell, resultNodes[i].Attributes[j].Value);
                                }
                                catch (Exception)
                                {

                                    ;
                                }

                            }
                            
                           
                        }
                        //  thisCell.RowHeight = 15;
                        Console.SetCursorPosition(curLeft, curTop);
                        Console.Write(string.Format("Generating Excel Report : {0:0.00}%    ", ((double)i/ (double)resultNodes.Count)*100));
                       
                    }

                    thisCell.Worksheet.Rows.RowHeight = 15;
                   

                }
            }
            catch (Exception)
            {

                return false;
            }

            return true;
        }

        public static string GetOutXMLFileName(string configName)
        {
            if (!Directory.Exists("TestResults"))
            {
                Directory.CreateDirectory("TestResults");
            }
            string timeStamp = DateTime.Now.ToString("s").Replace("-", "").Replace(":", "").Replace(" ","");
            string outputFileName = string.Empty;
            outputFileName = configName.Replace(@"TestConfigs\", @"TestResults\");
            outputFileName = outputFileName.Replace(@"TestConfig", @"TestResult");
            outputFileName = outputFileName.Replace(".xml", "." + timeStamp + ".xml");
            
            return outputFileName;
        }
    }
}
